package spark;

import com.google.gson.Gson;
import core.MoveOrNot;
import log.WriteToLog;
import org.apache.hadoop.hbase.util.Bytes;
import singleobject.MemoryInfo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/*
 * 服务器线程处理类
 */
public class ServerThread extends Thread {
// 和本线程相关的Socket
Socket socket = null;
private Gson gson = new Gson();
public ServerThread(Socket socket) {
    this.socket = socket;
}

//线程执行的操作，响应客户端的请求
public void run(){
    WriteToLog.write("Server Thread is running.");
    InputStream is=null;
    InputStreamReader isr=null;
    BufferedReader br=null;
    OutputStream os=null;
    PrintWriter pw=null;
    try {
        //获取输入流，并读取客户端信息
        is = socket.getInputStream();
        isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
        String info=null;
        while((info=br.readLine())!=null){//循环读取客户端的信息
            TaskRegion taskRegion = gson.fromJson(info, TaskRegion.class);
            //type=false代表任务开始，true是任务结束
            if(taskRegion.isType()){
                System.out.print("task is over");
                WriteToLog.write("task is over.");
                MemoryInfo.getTASK().removeTaskRS(String .valueOf(taskRegion.getTaskId()));
                MemoryInfo.getREGION().removeRegionTask(String .valueOf(taskRegion.getTaskId()));
            }else {
                System.out.print("task comes");
                WriteToLog.write("task comes.");
                MemoryInfo.getTASK().addTaskRS(String .valueOf(taskRegion.getTaskId()),taskRegion.getHost());
                MemoryInfo.getREGION().addRegionTask(String .valueOf(taskRegion.getTaskId()), taskRegion.getTableName(),taskRegion.getStartKey(),taskRegion.getEndKey());
                System.out.println("startkey:"+taskRegion.getStartKey());
                System.out.println("endkey:"+taskRegion.getEndKey());
            }
            //System.out.println(taskRegion);
        }
        socket.shutdownInput();//关闭输入流
        //获取输出流，响应客户端的请求
        os = socket.getOutputStream();
        pw = new PrintWriter(os);
        pw.flush();//调用flush()方法将缓冲输出
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        //关闭资源
        try {
            if(pw!=null)
                pw.close();
            if(os!=null)
                os.close();
            if(br!=null)
                br.close();
            if(isr!=null)
                isr.close();
            if(is!=null)
                is.close();
            if(socket!=null)
                socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}
